import { Logger } from '@ones-op/node-logger'

import type { PluginRequest, PluginResponse } from '@ones-op/node-types'
import { fetchONES } from '@ones-op/node-fetch'
// 使用 @ones-op/fetch 会出现循环依赖的问题
// import { OPFetch } from '@ones-op/fetch'

interface StatusProps {
  uuid: string
  name: string
  name_pinyin: string
  category: string
  built_in: boolean
  detail_type: number
  create_time: number
}

async function getTaskStatus(teamId: string): Promise<StatusProps[]> {
  const url = `/team/${teamId}/task_statuses`
  const response = await fetchONES({
    path: url,
    method: 'GET',
  })

  const list = (response?.body as any).task_statuses
  return list
}

export async function taskPreAction(request: any): Promise<PluginResponse> {
  const teamUUID = request?.teamUUID
  // 先获取工作项状态列表
  const statuList: StatusProps[] = await getTaskStatus(teamUUID)
  // getTaskStatus(teamUUID)
  const body = request?.body as any
  // console.log(JSON.stringify(request))
  const events = body.task_events
  // 工作项UUID
  const taskId = events[0].task_uuid
  Logger.info('taskId', taskId)

  // 标题
  const titleField = events[0].task_fields.find((field: any) => field.field_uuid === 'field001')
  if (titleField) {
    Logger.info('标题', titleField.value)
  }

  // 工作项状态UUID
  const statusField = events[0].task_fields.find((field: any) => field.field_uuid === 'field005')
  if (statusField) {
    Logger.info('工作项状态UUID', statusField.value)
    // 需要接口去查询状态的名称
    const statusName = statuList.find((status: any) => status.uuid === statusField.value)
    Logger.info('工作项状态名称', statusName?.name)
  }
  return {
    statusCode: 200,
    body: {
      code: 200,
      body: {
        is_follow: true,
        is_reject: false,
        reject_reason: 'Reason for refusal',
        task_events: events,
        other_data: 'other data',
      },
    },
  }
}

export async function taskActionDone(request: PluginRequest): Promise<PluginResponse> {
  // 这个是数据保存后再调用的
  // console.log('taskActionDone')
  // const body = request?.body as any
  // const events = body.task_events
  // const otherData = body.other_data
  // const userUUID = body.user_uuid
  // const lang = body.lang
  // const action = events[0].action
  // Logger.info('ans event', events)
  // Logger.info('ans other_data', otherData)
  // Logger.info('ans userID:', userUUID)
  // Logger.info('ans lang', lang)
  // Logger.info('ans action', action)
  return {
    statusCode: 200,
    body: {
      code: 200,
    },
  }
}
